package com.cqjtu.eecs.handler;

import com.alibaba.fastjson.JSON;
import com.cqjtu.eecs.service.impl.RedisService;
import com.cqjtu.eecs.utils.JwtUtils;
import com.cqjtu.eecs.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 用户登录成功处理类
 * @author luojun
 * @since 2022-03-05
 * 返回token给用户
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication
    ) throws IOException, ServletException {
        // 获取当前登录的用户信息
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("用户{}登录成功",user.getUsername());
        // 创建token
        String token = JwtUtils.createToken(user);
        // 在redis中缓存权限
        redisService.setEXString(user.getUsername(),
                JSON.toJSONString(user.getAuthorities()),
                Integer.toUnsignedLong(JwtUtils.EXPIRATION));
//        httpServletResponse.setHeader(JwtUtils.HEADER, token);
        httpServletResponse.getWriter().print(JSON.toJSONString(Result.success(token)));
    }
}
